import '../../public.dart';

class ChangePasswordPage extends StatefulWidget {
  const ChangePasswordPage({super.key});

  @override
  State<ChangePasswordPage> createState() => _ChangePasswordPageState();
}

class _ChangePasswordPageState extends State<ChangePasswordPage> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  String? currentPassword;
  String? newPassword;
  String? confirmPassword;
  bool _isCurrentObscure = true;
  bool _isNewObscure = true;
  bool _isConfirmObscure = true;
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    final userModel = Provider.of<UserModel>(context);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black87),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          'Change Password',
          style: TextStyle(
            color: Colors.black87,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          _buildWelcomeSection(),
          Form(
            key: formKey,
            child: Column(
              children: [
                _buildCurrentPasswordField(),
                _buildNewPasswordField(),
                _buildConfirmPasswordField(),
                const SizedBox(height: 40),
                _buildChangePasswordButton(userModel),
                const SizedBox(height: 20),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWelcomeSection() {
    return Container(
      padding: const EdgeInsets.all(30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 30),
          Text(
            'Update Password',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            'Please enter your current password and choose a new secure password',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildCurrentPasswordField() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Current Password',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Colors.grey[700],
            ),
          ),
          const SizedBox(height: 8),
          TextFormField(
            obscureText: _isCurrentObscure,
            keyboardType: TextInputType.text,
            onSaved: (value) => currentPassword = value,
            onChanged: (value) => currentPassword = value,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your current password';
              }
              return null;
            },
            cursorWidth: 1.5,
            cursorColor: const Color.fromRGBO(51, 51, 51, 1),
            decoration: InputDecoration(
              hintText: 'Enter your current password',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 12,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  _isCurrentObscure ? Icons.visibility : Icons.visibility_off,
                  color: Colors.grey[500],
                ),
                onPressed: () {
                  setState(() {
                    _isCurrentObscure = !_isCurrentObscure;
                  });
                },
              ),
            ).copyWith(fillColor: Colors.grey.shade50),
          ),
        ],
      ),
    );
  }

  Widget _buildNewPasswordField() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'New Password',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Colors.grey[700],
            ),
          ),
          const SizedBox(height: 8),
          TextFormField(
            obscureText: _isNewObscure,
            keyboardType: TextInputType.text,
            onSaved: (value) => newPassword = value,
            onChanged: (value) => newPassword = value,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter a new password';
              }
              if (value.length < 6) {
                return 'Password must be at least 6 characters';
              }
              return null;
            },
            cursorWidth: 1.5,
            cursorColor: const Color.fromRGBO(51, 51, 51, 1),
            decoration: InputDecoration(
              hintText: 'Enter your new password',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 12,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  _isNewObscure ? Icons.visibility : Icons.visibility_off,
                  color: Colors.grey[500],
                ),
                onPressed: () {
                  setState(() {
                    _isNewObscure = !_isNewObscure;
                  });
                },
              ),
            ).copyWith(fillColor: Colors.grey.shade50),
          ),
        ],
      ),
    );
  }

  Widget _buildConfirmPasswordField() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Confirm New Password',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Colors.grey[700],
            ),
          ),
          const SizedBox(height: 8),
          TextFormField(
            obscureText: _isConfirmObscure,
            keyboardType: TextInputType.text,
            onSaved: (value) => confirmPassword = value,
            onChanged: (value) => confirmPassword = value,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please confirm your new password';
              }
              if (value != newPassword) {
                return 'Passwords do not match';
              }
              return null;
            },
            cursorWidth: 1.5,
            cursorColor: const Color.fromRGBO(51, 51, 51, 1),
            decoration: InputDecoration(
              hintText: 'Confirm your new password',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 12,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  _isConfirmObscure ? Icons.visibility : Icons.visibility_off,
                  color: Colors.grey[500],
                ),
                onPressed: () {
                  setState(() {
                    _isConfirmObscure = !_isConfirmObscure;
                  });
                },
              ),
            ).copyWith(fillColor: Colors.grey.shade50),
          ),
        ],
      ),
    );
  }

  Widget _buildChangePasswordButton(UserModel userModel) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: SizedBox(
        width: double.infinity,
        height: 50,
        child: ElevatedButton(
          onPressed: _isLoading ? null : () => _changePassword(userModel),
          style: ButtonStyle(
            shape: WidgetStateProperty.all(
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            ),
            backgroundColor: WidgetStateProperty.all(Colors.black),
            minimumSize: WidgetStateProperty.all(
              const Size(double.infinity, 50),
            ),
          ),
          child: _isLoading
              ? const SizedBox(
                  height: 24,
                  width: 24,
                  child: CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 2,
                  ),
                )
              : const Text(
                  'UPDATE PASSWORD',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
        ),
      ),
    );
  }

  void _changePassword(UserModel userModel) async {
    final form = formKey.currentState;
    if (form!.validate()) {
      form.save();
      setState(() {
        _isLoading = true;
      });

      try {
        await ClientUserApi.changePassword_1(
          ChangePasswordDto(
            currentPpassword: currentPassword!,
            newPpassword: newPassword!,
          ),
        );

        if (mounted) {
          Toast.show('Password changed successfully');
          Navigator.of(context).pop();
        }
      } catch (e) {
        if (mounted) {
          Toast.show('Failed to change password: $e');
        }
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }
}
